package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.ArDAO;
import mwa.cs.dao.CustomerClassDAO;
import mwa.cs.dao.GenDocDAO;
import mwa.cs.dao.RcTransDDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Ar;
import mwa.cs.model.RcTransD;
import mwa.cs.model.RcTransM;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS51001Srvl
 */
public class CS51001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private double vnSumTotalAll = 0.00;
	private double vnSumVatAmount = 0.00;
	//private double vnSumBillAmount = 0.00; 
	private String vaAccountCode;
	private String vaUrlAddress = "";
	private String vaAgentBrowser = "";
	

    public CS51001Srvl() {
        super();
    }

	@SuppressWarnings("unchecked")
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	String vaBtnSearchAcoount = request.getParameter("btn_search_account");
    	String vaBtnSave = request.getParameter("btn_save");
    	String vaBillNumber = request.getParameter("inputBillNumber");
    	String vaHidePayerName = request.getParameter("inputPayerName");	
    	String vaCheckboxPassJSonData = request.getParameter("voArrCheckedValue");
    	String vaCheckboxPassScreenData[]  = request.getParameterValues("chkChoose");
    	String vaBtn_close = request.getParameter("btn_closePage");
		double vaPenalty = 0.0;
		int vnClickCounter = -1;
    	boolean vbUsedJSon = false;
    	if ( vaBtnSearchAcoount != null && vaBtnSearchAcoount.trim().equals("yes")){
    		findArDataProcess(request, vaBillNumber);
    		// call clickCounter, go back to history page
    		clickCounter(vnClickCounter, request);
    	} else if ( vaBtnSave != null && vaBtnSave.equals("yes")){
    		updateArData(vnSiteId,  vaHidePayerName, vaCheckboxPassScreenData, request);
    		// call clickCounter, go back to history page
    		clickCounter(vnClickCounter, request);
    	} else if ( vaCheckboxPassJSonData != null){
    		DecimalFormat voDecimalFormat = new DecimalFormat("###,##0.00");
    		double vnSumVatAmount = 0.0, vnSumBillAmount = 0.0, vnSumTotalAmount = 0.0, vnSumGarbage = 0.0, vnSumWasteWater = 0.0, vnSumOther = 0.0, vnGrossAmount = 0.0;
    		String[] voAllSumResult = null;
    		String[] voCheckbox = null;
    		
    		// Data from JSP Page mean of vaCheckboxPassJSonData
    		voCheckbox = vaCheckboxPassJSonData.split(",");
    		
    		// check penalty
    		try {
    	    	vaPenalty = Double.parseDouble(request.getParameter("inputPenalty"));
			} catch (Exception e) {
				e.getMessage();				
			}
    		
    		// get check box data and parse to double for calculate
    		try {
    			for (int i = 0; i < voCheckbox.length; i++){
        			String[] voOnCheckedData =  voCheckbox[i].split("/");
        			vnSumGarbage += Double.parseDouble(voOnCheckedData[5]);
        			vnSumWasteWater += Double.parseDouble(voOnCheckedData[6]);
        			vnSumOther += Double.parseDouble(voOnCheckedData[7]);
        			vnSumVatAmount += Double.parseDouble(voOnCheckedData[8]);
        			vnSumBillAmount += Double.parseDouble(voOnCheckedData[9]);
        			vnSumTotalAmount += Double.parseDouble(voOnCheckedData[10]);
        		}
			} catch (Exception e) {
				e.getMessage();
			}
    		
    		// sum gross
			vnGrossAmount = vaPenalty + vnSumTotalAmount;
    		voAllSumResult = new String[]{ String.valueOf(voDecimalFormat.format(vnSumGarbage)), String.valueOf(voDecimalFormat.format(vnSumWasteWater)),
    									   String.valueOf(voDecimalFormat.format(vnSumOther)), String.valueOf(voDecimalFormat.format(vnSumVatAmount)), 
    									   String.valueOf(voDecimalFormat.format(vnSumBillAmount)) ,String.valueOf(voDecimalFormat.format(vnSumTotalAmount)),
    									   String.valueOf(voDecimalFormat.format(vnGrossAmount))};
    		PrintWriter voOut = response.getWriter();
    		
    		// add data to JSon Object
    		try {
    			JSONObject voObject = new JSONObject();
    			JSONArray voArrayData = new JSONArray();
    			for ( int i = 0; i < voAllSumResult.length; i++){
    				voArrayData.add(voAllSumResult[i]);
    			}
    			voObject.put("voJSonResult",voArrayData );
    			voOut.print(voObject.toJSONString());
    		} finally {
    			voOut.close();
    			vbUsedJSon = true;
    		}
    	} else if ( vaBtn_close != null && vaBtn_close.equals("yes")){
    		// back to history page
			session.setAttribute("vnClick", -1);
    	}
    	// Direct to JSP Page 
    	if ( vbUsedJSon == false){
    		RequestDispatcher rd = request.getRequestDispatcher("CS51001.jsp");
    		rd.forward(request, response); 
    	}
    }
	
	// count click when onClick
    private void clickCounter(int vnClickCounter, HttpServletRequest request) {
		HttpSession session = request.getSession();
		if ( session.getAttribute("vnClick") != null){
			vnClickCounter = Integer.parseInt(session.getAttribute("vnClick").toString());
			vnClickCounter = vnClickCounter + (-1);
		} else {
			vnClickCounter += -1;
		}
		session.setAttribute("vnClick", vnClickCounter);	
	}
	// On click save button from Screen
	private void updateArData(int vnSiteId, String vaPayerName, String[] voCheckbox, HttpServletRequest request) {
		Database db = new Database();
		ArDAO voArDAO =  new ArDAO(db);
		GenDocDAO voGenDocDAO = new GenDocDAO(db);
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
		String vnSerialNumber = voGenDocDAO.generatingNextSNDoc(vnSiteId, JDate.getMonth(),JDate.getYear() );
		
		// Check Back Time 
		String vaReceiveTimeToDB = JDate.getTime();
		String vaReceiveDateToDB = JDate.checkBackTimeDate(vnSiteId);		
		try {
			String vnPenaltyTemp = "";
			if( request.getParameter("inputPenalty").trim().toString().equals("")){
				vnPenaltyTemp = "0.00";
			} else {
				vnPenaltyTemp =  request.getParameter("inputPenalty").trim().toString();
			}
			double vnPenalty = Double.parseDouble( vnPenaltyTemp);
			RcTransM voRcTansM = new RcTransM();
			voRcTansM.setVnSiteId(vnSiteId);
	 		voRcTansM.setVaAccount(vaAccountCode);
	 		voRcTansM.setVnSerialNumber(Long.parseLong(vnSerialNumber));
	 		voRcTansM.setVaPayerName( request.getParameter("vaHidePayerName"));
	 		voRcTansM.setVaPayerAddress( request.getParameter("vaHideAddress"));
	 		voRcTansM.setVnNetAmount(( vnSumTotalAll + vnPenalty) - vnSumVatAmount);
	 		voRcTansM.setVnGrossAmount( vnSumTotalAll + vnPenalty);
	 		voRcTansM.setVnVatAmount( vnSumVatAmount);
	 		voRcTansM.setVaStatus("");
	 		voRcTansM.setVnPenalty( vnPenalty);
	 		voRcTansM.setVaReceiveDate(vaReceiveDateToDB);
	 		voRcTansM.setVaReceiveTime(vaReceiveTimeToDB);
	 		voRcTansM.setVnInsertUserId(vnUserId);
	 		voRcTansM.setVaInsertDate(JDate.getDate());
	 		voRcTansM.setVaInsertTime(JDate.getTime());
	 		voRcTansM.setVnReceiveEmployee(vnUserId);
    		db.beginTransaction();	
			voRcTransMDAO.insertRcTransM(voRcTansM);
    		for (int i = 0; i < voCheckbox.length; i++){
    			String[] voTemp =  voCheckbox[i].split("/");
    			String vaAccountTemp = voTemp[1];
    			String vaBillNumberTemp = voTemp[2];
    			//
    			RcTransD voRcTansD = new RcTransD();
    			voRcTansD.setVnSiteId(vnSiteId);
    			voRcTansD.setVnSerialNumber(voRcTansM.getVnSerialNumber());
    			voRcTansD.setVnSeqNumber(Integer.parseInt(voTemp[0]));
    			voRcTansD.setVnBillAmount(Double.parseDouble(voTemp[5])+Double.parseDouble(voTemp[6])+Double.parseDouble(voTemp[7])+Double.parseDouble(voTemp[9]));
    			voRcTansD.setVnVatAmount(Double.parseDouble(voTemp[8]));
    			voRcTansD.setVaBillNumber(vaBillNumberTemp);
    			voRcTansD.setVaReceiveCode("21");
    			voRcTansD.setVnWaterCharge(Double.parseDouble(voTemp[3]));
    			voRcTansD.setVnWaterFee(Double.parseDouble(voTemp[4]));
    			voRcTansD.setVnGarbageCharge(Double.parseDouble(voTemp[5]));
    			voRcTansD.setVnWasteWaterCharge(Double.parseDouble(voTemp[6]));
    			voRcTansD.setVnOtherCharge(Double.parseDouble(voTemp[7]));
    			voRcTansD.setVnInsertUserId(vnUserId);
    			voRcTansD.setVaInsertDate(JDate.getDate());
    			voRcTansD.setVaInsertTime(vaReceiveTimeToDB);		
    			voRcTransDDAO.insertRcTransD( voRcTansD);   					
    			// Update AR
    			voArDAO.UpdateAr(vnSiteId, vnUserId, vaReceiveDateToDB, vaReceiveTimeToDB, vaPayerName ,vaBillNumberTemp, vaAccountTemp, vnSerialNumber);
    		}
    		db.commit();
    	} catch (Exception e) {
    		SMErrorLogDAO.getInstance().addLog(0, "CS51001", JDate.getDate(), JDate.getTime(),vnUserId, "CS51001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);	
    		db.rollback();
    	} finally {
    		db.close(); 
    	}
	}
	
	
	// On click search button from Screen
	@SuppressWarnings("unused")
	private void findArDataProcess(HttpServletRequest request, String vaBillNumber) {
    	String vaFindStatus = "yes" ;
		Database db = new Database();
		ArDAO voArDAO =  new ArDAO(db);
		ArrayList<Ar> voArList = new ArrayList<Ar>();
		CustomerClassDAO voCustomerClassDAO = new CustomerClassDAO(db);
		List<Map<String, Object>> voArResult ;
		String vaCurrentDate = JDate.getDay()+"/"+JDate.getMonth()+"/"+JDate.getYear();
		String vaAccountName="", vaAccount="", vaCustomerAddress="", vaCustomerClass="", vaReceivableDate = "";
		double vnVatAmount = 0.00, vnBillAmount = 0.00, vnGrabage = 0.00 , vnWasteWater = 0.00, vnOther = 0.00, vnTotalAmount = 0.00;
		double vnGarbageTotal = 0.00, vnOtherTotal = 0.00, vnWasteWaterTotal = 0.00, vnVatTotal = 0.00, vnBillAmountTotal = 0.00, vnSumTotal = 0.00;
    	vaAccountCode = request.getParameter("inputAccountName");
		if ( vaAccountCode.trim() != "" && vaBillNumber.trim().equals("") ){
			voArResult = voArDAO.findArDataByAccountCode(vnSiteId,vaAccountCode);
//			System.out.println("case 1");
		} else if( vaBillNumber.trim() !="" && vaAccountCode.trim().equals("") ){
			voArResult = voArDAO.findArDataByBillNumber(vnSiteId,vaBillNumber);
//			System.out.println("case 2");
		}else {
			voArResult = voArDAO.findArDataByAccountCodeAndBillNumber(vnSiteId, vaBillNumber, vaAccountCode);
//			System.out.println("case 3");
		}	
		if ( voArResult.isEmpty()){
			vaCurrentDate = "";
			vaFindStatus = "notFind";
		}
		for ( int i = 0; i < voArResult.size(); i++){
			Ar voAR = new Ar();
			Map<String, Object> voArObject = voArResult.get(i);
			vaAccount = voArObject.get("ACCOUNT").toString();
			String vaPName = "";
			try {
				vaPName = voArObject.get("PNAME").toString();
			} catch (Exception e) {	
				vaPName = "";
			}
			vaAccountName = vaPName +" "+ voArObject.get("FNAME").toString()+" "+voArObject.get("LNAME").toString();
			vaCustomerClass = voCustomerClassDAO.findDescriptionBySiteAndCode(vnSiteId, voArObject.get("CUSTOMER_CLASS").toString());
			vaCustomerAddress = voArObject.get("ADDRESS").toString();
			voAR.setVaAccount(vaAccount);
			voAR.setVaBillNumber( voArObject.get("BILL_NUMBER").toString());
			vaReceivableDate = voArObject.get("ACCOUNT_RECEIVABLE_DATE").toString();
			vaReceivableDate = vaReceivableDate.substring(6,8)+"/"+vaReceivableDate.substring(4,6)+"/"+vaReceivableDate.substring(0,4);
			voAR.setVaAccountReceivableDate( vaReceivableDate);
			voAR.setVnWaterCharge(Double.parseDouble(((BigDecimal) voArObject.get("WATER_CHARGE")).toString()));
			voAR.setVnWaterFee(Double.parseDouble(((BigDecimal) voArObject.get("WATER_FEE")).toString()));
			vnVatAmount = Double.parseDouble(((BigDecimal) voArObject.get("VAT_AMOUNT")).toString());
			voAR.setVnVatAmount(vnVatAmount);
			vnVatTotal += vnVatAmount;
			voAR.setVnBillAmount(vnBillAmount);
			vnBillAmount = Double.parseDouble(((BigDecimal) voArObject.get("BILL_AMOUNT")).toString());
			voAR.setVnBillAmount( vnBillAmount );
			vnBillAmountTotal += vnBillAmount;
			vnGrabage = Double.parseDouble(((BigDecimal) voArObject.get("GARBAGE_CHARGE")).toString());
			voAR.setVnGarbageCharge(vnGrabage);
			vnGarbageTotal += vnGrabage;
			vnWasteWater = Double.parseDouble(((BigDecimal) voArObject.get("WASTEWATER_CHARGE")).toString());
			voAR.setVnWasteWaterCharge(vnWasteWater);
			vnWasteWaterTotal += vnWasteWater;
			vnOther = Double.parseDouble(((BigDecimal) voArObject.get("OTHER_CHARGE")).toString());
			voAR.setVnOtherCharge(vnOther);
			vnOtherTotal += vnOther;
			vnTotalAmount = Double.parseDouble(((BigDecimal) voArObject.get("TOTAL_AMOUNT")).toString());
			voAR.setVnTotalAmount(vnTotalAmount);
			vnSumTotal += vnTotalAmount;
			voArList.add(voAR);
		}
		vnSumVatAmount = vnVatTotal;
		vnSumTotalAll = vnSumTotal;	
		//vnSumBillAmount = vnBillAmountTotal;
		db.close();
    	request.setAttribute("voArList", voArList);
		request.setAttribute("vaCurrentDate", vaCurrentDate);
		request.setAttribute("vaAccountName", vaAccountName);
		request.setAttribute("vaAccount", vaAccount);
		request.setAttribute("vaCustomerAddress", vaCustomerAddress);
		request.setAttribute("vaCustomerClass", vaCustomerClass);
		request.setAttribute("vaFindStatus", vaFindStatus);
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
